$(document).ready(function() {
	$.datepicker.regional['pt'] = {
			closeText: 'Fechar',
			prevText: '<',
			nextText: '>',
			currentText: 'Hoje',
			monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho',
			'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
			monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
			'Jul','Ago','Set','Out','Nov','Dez'],
			dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S&aacute;bado'],
			dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
			dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','S&aacute;b'],
			weekHeader: 'Sem',
			dateFormat: 'dd/mm/yy',
			firstDay: 0,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''
	};
	$.datepicker.setDefaults($.datepicker.regional['pt']);
	
	// mensagens para as datatables
	$.tableEmptyMessage = $("<div>")
		.addClass("alert alert-warning")
		.css("text-align", "center")
		.html('Nenhum registro encontrado.');
	
	// maximo de registro nas datatables
	$.maxRows = 12;
	
	// controle geral para links que deletam registros
	$('*[data-method="delete"]').click(function() {
		var f = document.createElement('form');
		$(this).after($(f).attr({
	        method: 'post',
	        action: $(this).attr('href')
		}).append('<input type="hidden" name="_method" value="DELETE" />'));
		
		$(f).submit();
		
		return false;
	});
	
	$("body").delegate('.btnRemoveComponent', 'click', function() {
		$(this).closest('.form-group').remove();				  
	});
	
	$("body").delegate('.cboOperationType', 'change', function() {
		var txtCigamCode = $(this).closest('.form-group').find('.txtCigamCode');
		if ($(this).val() == 1) {
			txtCigamCode.val('INSUMO')
			txtCigamCode.attr('readonly', 'readonly');
		} else {
			txtCigamCode.val('')
			txtCigamCode.removeAttr('readonly');			
		}
	});
	
	// datas
	$('.form-horizontal .input-group.date input').datepicker();
	$('.form-horizontal .input-group.date .input-group-addon').each(function(index, elm) {
		$(elm).click(function(){
			$(this).parent().find('input').datepicker().focus();
		});
	})
	
	$('.input-group.date input').mask('99/99/9999');
	
	// componentes com centro de custos
	$('#btnAddComponent').click(function() {
		var src = $('#tplNewComponentWithCostCentre').html(),
			tpl = Handlebars.compile(src) 
			newComponent = $(tpl());
		
		$(this).closest('.form-group').before(newComponent);
		
		var componentCodeField = $('input[name="cigamCodes[]"]', newComponent)
			componentNameField = $('input[name="components[]"]', newComponent)
			costCentresField = $('input[name="costCentres[]"]', newComponent),
			previousComponent = newComponent.prev(".component-group"); 

		if (previousComponent.length === 0) {
			componentCodeField.focus();
		} else {
			var previousCodeField = $('input[name="cigamCodes[]"]', previousComponent);
			if (previousCodeField.length === 0) {
				previousCodeField = $('input[name^="currentCigamCodes"]', previousComponent);	
			}
			if (previousCodeField.val() != "INSUMO") {
				componentCodeField.val(previousCodeField.val());
				componentNameField.focus();
			} else {
				componentCodeField.focus();
			}
			
		}
		
/*		componentNameField.autocomplete({
			source: function( request, response ) {
				$.ajax({
					url: $.rootUrl + "product/componentsSuggestions",
					data: {term: request.term},
					dataType: "json",
					success: function( data ) {
						response( $.map( data, function( item ) {
							return {
								label: item.code + ' - ' + item.name,
								name: item.name,
								value: item.costs_centres,
								code: item.code,
								isAccessory: item.accessory
							}
						}));
					}
				});
			},
			select: function( event, ui ) {
				var targetComponent = $(this).closest('.form-group');
				this.value = ui.item.name;
				$("select[name='accessories[]']", targetComponent).val(ui.item.isAccessory + "");
				$("input[name='cigamCodes[]']", targetComponent).val(ui.item.code);
				$("input[name='costCentres[]']", targetComponent).val($(ui.item.value).map(function() { return this.id; }).get().join());
				event.preventDefault();
			},
			focus: function (event, ui) {
				this.value = ui.item.name;
				event.preventDefault();
			},
			minLength: 3,
			delay: 200
		});*/
		
		$(".btnRemoveComponent", newComponent).tooltip();
		
		var defaultValue = $(allCostsCentres).map(function() { return this.id; }).get().join();
		costCentresField.val(defaultValue);
		costCentresField.costsCentres({ costsCentres: allCostsCentres });
	});
	
	$("[id^=btn-save]").click(function() {
		var btn = $(this)
	    btn.button('loading');
		
		window.setTimeout(function() { btn.button('reset') }, 2000);
	});
});